﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using SYSoft.Comm;
using SYSoft.Comm.DB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SYSoft.ServiceExtensions
{
    /// <summary>
    /// SqlSugar 启动服务
    /// </summary>
    public static class SqlsugarSetup
    {
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddScoped<ISqlSugarClient>(o =>
            {
                SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = BaseDBConfig.ConnectionString,//必填, 数据库连接字符串
                    DbType = (SqlSugar.DbType)BaseDBConfig.DbType,//必填, 数据库类型
                    IsAutoCloseConnection = true,//默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                    // 自定义特性 主键是自增key
                    ConfigureExternalServices = new ConfigureExternalServices()
                    {
                        EntityService = (property, column) =>
                        {
                            if (column.IsPrimarykey && property.PropertyType == typeof(int))
                            {
                                column.IsIdentity = true;
                            }
                        }
                    },
                    InitKeyType = SqlSugar.InitKeyType.Attribute// 字段信息读取, 如：该属性是不是主键，标识列等等信息
                });

                ////添加Sql打印事件，开发中可以删掉这个代码
                //db.Aop.OnLogExecuting = (sql, pars) =>
                //{
                //    Console.WriteLine(sql); 
                //};

                db.Aop.OnError = (exp) =>//SQL报错
                {
                    LogHelper.Error(exp.Message);
                    Console.WriteLine(exp);
                    //exp.sql 这样可以拿到错误SQL            
                };
                return db;
            });
        }
    }
}
